<template>
    <ECharts
        :options="options"
        :default-options="defaultOptions"
        class="echart-line"
    />
</template>
<script setup lang="ts">
import ECharts from '@/components/ECharts/index.vue'
import { computed, ref, watch } from 'vue'
import { options as defaultOptions } from './echarts.config'

const props = defineProps({
    option: { type: Object, default: null },
    title: { type: String, default: '' },
    data: { type: Array, default: () => [] },
})
const xData = ref<string[]>([])
const yData = ref<{ [key: string]: number[] }>({})
const zData = ref<string[]>([])

const filterData = (data: any[]) => {
    // 清除旧数据
    xData.value.splice(0, xData.value.length)
    yData.value = {}
    zData.value.splice(0, zData.value.length)
    data.forEach((item) => {
        let xIndex = xData.value.findIndex((it) => it === item.x)
        let zIndex = zData.value.findIndex((it) => it === item.z)
        if (xIndex < 0) {
            xData.value.push(item.x)
            xIndex = xData.value.length - 1
        }
        if (zIndex < 0) {
            zData.value.push(item.z)
            yData.value[item.z] = []
            zIndex = zData.value.length - 1
        }
        yData.value[item.z][xIndex] = item.y
    })
}
watch(
    () => props.data,
    (value) => {
        filterData(value)
    }
)

const options = computed(() => {
    if (props.option) return props.option
    const option: {
        legend?: any
        title: { text?: string }
        xAxis: {
            data: string[]
        }
        series: {
            name: string
            type: string
            data: number[]
        }[]
    } = {
        title: {},
        xAxis: {
            data: xData.value,
        },
        series: zData.value.map((item) => {
            return {
                name: item,
                type: 'line',
                data: yData.value[item],
            }
        }),
    }
    if (props.title) {
        option.title['text'] = props.title
    }
    if (zData.value.length) option['legend'] = {}
    return option
})
</script>
<style lang="scss" scoped>
.echart-line {
    width: 60vw;
    height: 30vh;
}
</style>
